// /pages/goods_cart/index.js
import {
    ReDistributionMall
} from "../../api/shipping.js"
import {
    getNavigationbar
} from "../../api/index.js"
Page({
    options: {
        styleIsolation: 'shared'
    },
    /**
     * 页面的初始数据
     */
    data: {
        height: "",
        isEdit: false,
        scrollViewHeight: 0, // 滚动区域高度
        tabbarHeight: 0, // 底部tabbar高度
        allCheckSelVal: false, // 当前全选状态
        supCheckSelVal: false, // 当前供应商选中状态
        cartList: [],
        cartTotalPrice: "0.0", // 购物车总价格
        checkGoodsList: [],
        isSpecs: false, // 商品规格弹窗打开状态
        isPopups: false, // 默认弹窗打开状态
        showFooter: false, // 是否显示确认按钮
        popupType: "", // 弹窗类型
        isChangingNum: false,
        cartidsList: [],
        zPactive: 1,addresid:0,
        showModal: false,
        totalNumbers: 0,
        isSlot: false,
        modalTitle: "",
        message: "",
        confirmText: "",addser:'',
        cancelText: "",
        showCancelButton: false,
        // 模拟购物车价格变动提示
        price: 0,
    },

    /**
     * 编辑购物车回调函数方法
     */
    handleEditCart() {
        const state = !this.data.isEdit
        this.setData({
            isEdit: state,
        })
    },
    /**
     * 打开商品规格弹窗回调函数方法
     */
    handleSelSpecs(e) {
        console.log('e', e)
        let data = {
            ...e.currentTarget.dataset.value
        }
        //详细接口
        getNavigationbar({
            act: 'good_detail',
            id: data.id
        }).then(res => {
            data = {
                ...res,
                ...e.currentTarget.dataset.value,
                tips: 1
            }
            console.log('详细接口', res)
            this.setData({
                isSpecs: true,
                objData: data
            })
        })

        wx.hideTabBar()
    },
    /**
     * 换促销回调函数方法
     */
    handleSelPromo(e) {
        const {
            type
        } = e.currentTarget.dataset
        this.setData({
            height: "880rpx",
            popupType: type,
            isPopups: true
        })
        wx.hideTabBar()
    },
    handlZp() {
        wx.navigateTo({
          url: '/pages/address_management/index?data=1',
        })
    },
    /**
     * 换促销回调函数方法(选择赠品)
     */
    handleSelZp(e) {
        const {
            index
        } = e.currentTarget.dataset
        this.setData({
            zPactive: index
        })
        getApp().$showTab()
    },
    /**
     * 更换赠品回调函数方法
     */
    handleReplaceZp(e) {
        const {
            type
        } = e.currentTarget.dataset
        if (this.data.zpList.length <= 0) {
            this.setData({
                height: "256rpx",
                popupType: type,
                showFooter: true,
                isPopups: true,
            })
        } else {
            this.setData({
                height: "880rpx",
                popupType: type,
                showFooter: true,
                isPopups: true,
            })
        }
        getApp().$showTab()
    },
    /**
     * 弹窗确认按钮回调函数方法
     */
    handleConfirm() {
        getApp().$showTab()
        this.setData({
            isSpecs: false
        })
    },
    /**
     * 关闭弹窗回调函数方法
     */
    handleClose() {
        this.setData({
            isPopups: false,
            isSpecs: false
        })
        getApp().$showTab()
    },

    /**
     * 进货商城收获地址列表
     */
    getAddressres(item) {
        getNavigationbar({
            act: 'addressres',
            p: '1',
            rol1page: 10000,
            type: 'getlist' //getlist-获取地址列表 editor-编辑 add-新增 singleaddr-根据id获取地址
        }).then(res => {
            res.forEach(element => {
                if(parseInt(element.is_default) == 1) {
                    console.log('this.data.params.province',this.data.params)
                    if(this.data.params != undefined) {
                        this.setData({
                            addser:this.data.params.province + this.data.params.address 
                        })
                        this.data.addresid = this.data.params.id
                        this.getShoppingCartList()
                    }else {
                        this.setData({
                            addser:element.province + element.address 
                        })
                        this.data.addresid = element.id
                    }
                   
                }
            });
            console.log('进货商城收获地址列表', res)

        })
    },
    /**
     * 购物车列表-一件代发
     */
    getMallCartsp(item) {
        ReDistributionMall({
            act: 'getMallCartsp',

        }).then(res => {
            console.log('购物车列表-一件代发', res)
            if (res.result == 101) {

            } else {

            }

        });
    },
    /**
     * 
     * 购物车列表-一件代发
     */
    getShoppingCartList(item) {
        ReDistributionMall({
            act: 'mallCartList',
            address_id: this.data.addresid,
            remove_postage: '1' || '',
        }).then(res => {
            res.lists.forEach(element => {
                console.log('elementitem', item)
                Object.assign(element, {
                    check: false,
                })
                element.brand.forEach(elementj => {
                    Object.assign(elementj, {
                        check: false,
                    })
                    elementj.lists.forEach(elementz => {
                        Object.assign(elementz, {
                            check: false,
                        })
                        ReDistributionMall({
                            act: 'handle_cartsgoods',
                            cartids: elementz.id,
                            flag: 2
                        }).then(res => {
                           
                        });
                    });
                });
            });

            if (res.result == 101) {

            } else {

            }
            
            this.data.cartList = res.lists
            console.log('购物车列表-一件代发', this.data.cartList)
            this.setData({
                cartList: res
            })
        });
    },
    /**
     * 提示弹窗确认回调函数方法
     */
    handleModalChange(e) {
        const type = e.detail
        if (type == "confirm") {
            this.setData({
                showModal: false
            })
        } else {
            this.setData({
                showModal: false
            })
            // getApp().Tips({ title: "操作已取消" })
        }
    },
    /**
     * 全选回调函数方法
     * @param {*} e 
     */
    allCheckSelChange(e) {
        console.log('allCheckSelVal', this.data.allCheckSelVal)
        // 购物车为空时无法勾选，返回重新校验
        if (this.data.cartList.lists.length == 0) return;
        // let check = e.detail;
        let check = !this.data.allCheckSelVal;
        let cartList = this.data.cartList.lists; // 获取购物车数据
        this.data.checkGoodsList = []; // 清空选中商品列表

        for (let i = 0; i < cartList.length; i++) {
            cartList[i].check = check; // 更改供应商选中状态
            let brandList = cartList[i].brand; // 获取购物车供应商下品牌数据
            for (let j = 0; j < brandList.length; j++) {
                brandList[j].check = check; // 更改品牌选中状态
                let goodsList = brandList[j].lists;
                for (let g = 0; g < goodsList.length; g++) {
                    goodsList[g].check = check;
                    if (goodsList[g].check) {
                        this.data.checkGoodsList.push(goodsList[g]); // push商品选中信息形成新数组
                        this.data.cartidsList.push({
                            id: goodsList[g].id,
                            numbers: goodsList[g].numbers
                        }); // push商品选中信息到cartidsList
                    } else {
                        let indexToRemove = this.data.cartidsList.findIndex(item => item.id === goodsList[g].id);
                        if (indexToRemove !== -1) {
                            const TNumbers = this.data.cartidsList.map(curr => curr.id).join(',');
                            console.log('TNumbers', TNumbers)
                            ReDistributionMall({
                                act: 'handle_cartsgoods',
                                cartids: TNumbers,
                                flag: 2
                            }).then(res => {
                                console.log('取消购物车商品操作', res)
                                this.data.cartidsList.splice(indexToRemove, 1); // 取消选中时从cartidsList中删除对应数据
                            });

                        }
                    }
                }
            }
        }
        console.log('this.data.cartidsList', this.data.cartidsList)
        this.setData({
            allCheckSelVal: check,
            cartList: this.data.cartList,
            checkGoodsList: this.data.checkGoodsList,
            cartidsList: this.data.cartidsList
        });

        this.getTotalPrice(); // 调用购物车计算规则
    },


    /**
     * 供应商选中回调函数方法
     * @param {*} e 
     */
    supCheckSelChange(e) {
        console.log('allCheckSelVal', this.data.allCheckSelVal)
        let index = e.currentTarget.dataset.value; // 获取当前供应商下标
        let cartList = this.data.cartList.lists; // 获取购物车数据
        let brandList = cartList[index].brand; // 获取购物车供应商下品牌数据

        if (cartList[index].check) {
            cartList[index].check = false;
            for (let i in brandList) {
                brandList[i].check = false;
                for (let j in brandList[i].lists) {
                    brandList[i].lists[j].check = false;
                    let indexToRemove = this.data.cartidsList.findIndex(item => item.id === brandList[i].lists[j].id);
                    if (indexToRemove !== -1) {
                        const TNumbers = this.data.cartidsList.map(curr => curr.id).join(',');
                        console.log('TNumbers', TNumbers)
                        ReDistributionMall({
                            act: 'handle_cartsgoods',
                            cartids: TNumbers,
                            flag: 2
                        }).then(res => {
                            console.log('取消购物车商品操作', res)
                            this.data.cartidsList.splice(indexToRemove, 1); // 取消选中时从checkGoodsList中删除对应数据
                        });

                    }
                }
            }
        } else {
            cartList[index].check = true;
            for (let i in brandList) {
                brandList[i].check = true;
                for (let j in brandList[i].lists) {
                    brandList[i].lists[j].check = true;
                    this.data.cartidsList.push({
                        id: brandList[i].lists[j].id,
                        numbers: brandList[i].lists[j].numbers
                    }); // push商品选中信息形成新数组
                }
            }
        }
        let allBrandsChecked = cartList.every(cart => cart.brand.every(brand => brand.check));
        console.log('this.data.cartidsList', this.data.cartidsList)
        // 重新赋值 渲染购物车数据
        this.setData({
            cartList: this.data.cartList,
            checkGoodsList: this.data.checkGoodsList,
            allCheckSelVal: allBrandsChecked // 更新全选按钮状态
        })
        // this.getAllCheck(); // 设置全选
        this.getTotalPrice(); // 调用购物车计算规则
    },
    /**
     * 品牌选中回调函数方法
     * @param {*} e 
     */
    brandCheckSelChange(e) {
        let index = e.target.dataset.value; // 获取当前品牌下标
        let cartList = this.data.cartList.lists; // 获取购物车数据
        let check = e.detail; // 复选框状态

        for (let i = 0; i < cartList.length; i++) {
            let brandList = cartList[i].brand;

            for (let j = 0; j < brandList.length; j++) {
                if (Number(brandList[j].brandid) === Number(index)) {
                    let goodsList = brandList[j].lists;

                    brandList[j].check = check; // 更新品牌选中状态

                    for (let g = 0; g < goodsList.length; g++) {
                        goodsList[g].check = check; // 更新品牌下的商品状态
                        if (!check) {
                            let indexToRemove = this.data.cartidsList.findIndex(item => item.id === goodsList[g].id);
                            if (indexToRemove !== -1) {
                                console.log('执行cartidsList', this.data.cartidsList)
                                const TNumbers = this.data.cartidsList.map(curr => curr.id).join(',');
                                console.log('TNumbers', TNumbers)
                                ReDistributionMall({
                                    act: 'handle_cartsgoods',
                                    cartids: TNumbers,
                                    flag: 2
                                }).then(res => {
                                    console.log('取消购物车商品操作', res)
                                    this.data.cartidsList.splice(indexToRemove, 1); // 取消选中时从cartidsList中删除对应数据
                                });


                            }
                        } else {
                            this.data.cartidsList.push({
                                id: goodsList[g].id,
                                numbers: goodsList[g].numbers
                            }); // 添加到cartidsList中
                        }
                    }

                    let brandCheckCount = brandList.filter(brand => brand.check).length; // 统计选中的品牌数量

                    if (brandCheckCount === brandList.length) {
                        cartList[i].check = true; // 更新供应商选中状态
                    } else {
                        cartList[i].check = false;
                    }
                }
            }
        }
        console.log('this.data.cartidsList', this.data.cartidsList)
        // 判断是否所有品牌都选中，若是则勾选全选按钮
        let allBrandsChecked = cartList.every(cart => cart.brand.every(brand => brand.check));
        console.log('cartList', cartList, allBrandsChecked)
        this.setData({
            cartList: this.data.cartList,
            allCheckSelVal: allBrandsChecked // 更新全选按钮状态
        });

        // this.getAllCheck(); // 设置全选
        this.getTotalPrice(); // 调用购物车计算规则
    },


    /**
     * 商品选中回调函数方法
     * @param {*} e 
     */

    goodsCheckSelChange(e) {
        let goodsId = e.currentTarget.dataset.value // 获取当前商品ID
        console.log('1', e)

        let cartList = this.data.cartList.lists // 获取购物车数据
        let check = e.detail // 复选框状态
        for (let i = 0; i < cartList.length; i++) {
            let brandList = cartList[i].brand
            for (let j = 0; j < brandList.length; j++) {
                let goodsList = brandList[j].lists

                for (let g = 0; g < goodsList.length; g++) {
                    if (goodsList[g].id === goodsId) {
                        // 判断当前商品是否已勾选
                        if (goodsList[g].check) {
                            let index = this.data.cartidsList.findIndex(item => item.id === e.target.dataset.id);
                            if (index > -1) {

                                const TNumbers = this.data.cartidsList.map(curr => curr.id).join(',');
                                ReDistributionMall({
                                    act: 'handle_cartsgoods',
                                    cartids: TNumbers,
                                    flag: 2
                                }).then(res => {
                                    console.log('取消购物车商品操作', res)
                                    this.data.cartidsList.splice(index, 1);
                                });
                            }
                            cartList[i].check = false // 更改供应商选中状态
                            brandList[j].check = false // 更改品牌选中状态
                            goodsList[g].check = false // 更改商品选中状态
                        } else {
                            console.log('进123', goodsList[g])
                            this.data.cartidsList.push({
                                id: e.target.dataset.id,
                                numbers: goodsList[g].numbers
                            });
                            this.data.checkGoodsList.push(goodsList[g]) // push商品选中信息形成新数组
                            goodsList[g].check = check // 更改商品选中状态
                            let goodsLength = brandList[j].lists.length // 获取品牌下商品数量
                            let goodsCheck = 0
                            // 遍历商品数据
                            for (let k in goodsList) {
                                if (goodsList[k].check) {
                                    goodsCheck++
                                }
                            }
                            // 根据勾选商品数据长度判断品牌是否全选
                            if (goodsLength === goodsCheck) {
                                brandList[j].check = true
                            }
                            let brandLength = cartList[i].brand.length // 获取供应商下品牌数量
                            let brandCheck = 0
                            // 遍历品牌数据
                            for (let k in brandList) {
                                if (brandList[k].check) {
                                    brandCheck++
                                }
                            }
                            // 根据勾选品牌数据长度判断供应商是否全选
                            if (brandLength === brandCheck) {
                                cartList[i].check = true // 更改供应商选中状态
                            }
                        }
                    }
                }
            }
        }
        console.log('this.data.cartidsList123', this.data.cartidsList)
        const totalNumbers = this.data.cartidsList.reduce((acc, curr) => acc + parseInt(curr.numbers), 0);
        console.log('totalNumbers', totalNumbers); // 输出结果为 9

        let allBrandsChecked = cartList.every(cart => cart.brand.every(brand => brand.check));
        // 重新渲染购物车数据
        this.setData({
            totalNumbers: totalNumbers,
            cartList: this.data.cartList,
            checkGoodsList: this.data.checkGoodsList, // 重新渲染选中商品存储对象数据
            allCheckSelVal: allBrandsChecked // 更新全选按钮状态
        })
        // this.getAllCheck() // 设置全选
        this.getTotalPrice() // 调用购物车计算规则
    },
    /**
     * 商品数量变化回调函数方法
     * @param {*} e
     */
    handleNumChange(e) {
        if (this.data.isChangingNum) {
            return; // 如果正在处理数量变化，则直接返回，避免重复操作
        }
        this.data.isChangingNum = true; // 设置标识位为true，表示正在处理数量变化

        let data = e.target.dataset.value;
        ReDistributionMall({
            act: 'addEditMallCart',
            productid: data.productid || '',
            propertyid: data.propertyid || '',
            numbers: e.detail || '',
        }).then(res => {
            console.log('添加编辑购物车-商品列表', res);
            if (res.result == 101) {
                wx.nextTick(() => {
                    getApp().Tips({
                        title: res.msg
                    });
                });
            } else {
                this.getTotalPrice(); // 调用购物车计算规则
                wx.nextTick(() => {
                    getApp().Tips({
                        title: "商品已添加至购物车"
                    });
                    this.getShoppingCartList();
                });
            }

            this.data.isChangingNum = false; // 处理完数量变化后，重置标识位为false
        });
        const totalNumbers = this.data.cartidsList.reduce((acc, curr) => acc + parseInt(curr.numbers), 0);
        this.setData({
            totalNumbers: totalNumbers,
        })
    },

    /**
     * 设置全选
     */
    getAllCheck() {
        let cartList = this.data.cartList // 获取购物车数据
        let length = cartList.length // 购物车数据数量长度
        let allCheckSelVal = this.data.allCheckSelVal // 当前全选状态
        let allCheck = 0
        for (let i = 0; i < cartList.length; i++) {
            if (cartList[i].check) {
                allCheck++
            }
        }
        if (length === allCheck) {
            allCheckSelVal = true
        } else {
            allCheckSelVal = false
        }
        this.setData({
            allCheckSelVal: allCheckSelVal
        })
        this.getTotalPrice()
    },

    /**
     * 计算选中状态下供应商品牌下的商品数量及总价格
     */
    getTotalPrice() {
        let totalPrice = 0; // 选中商品总价格
        let totalNum = 0; // 选中商品总数量
        let cartList = this.data.cartList.lists; // 购物车数据
        let promises = []; // 存储所有请求的Promise对象

        for (let i = 0; i < cartList.length; i++) {
            let brandList = cartList[i].brand;

            for (let j = 0; j < brandList.length; j++) {
                let goodsList = brandList[j].lists;

                for (let g = 0; g < goodsList.length; g++) {
                    // 判断商品是否选中
                    if (goodsList[g].check) {
                        let cartidsList = [{
                            id: goodsList[g].id,
                            sealmanid: goodsList[g].agentid
                        }];

                        let TNumbers = cartidsList.map(curr => curr.id).join(',');
                        promises.push(ReDistributionMall({
                            act: 'handle_cartsgoods',
                            cartids: TNumbers,
                            flag: 1
                        }));

                        let price = Number(goodsList[g].price); // 商品单价
                        totalPrice += price; // 计算每个商品的总价并累加
                    } else {
                        let index = this.data.cartidsList.findIndex(item => item.id === goodsList[g].id);
                        if (index > -1) {

                            this.data.cartidsList.splice(index, 1);
                        }
                    }
                }
            }
        }

        Promise.all(promises).then(responses => {
            responses.forEach(res => {
                console.log('选中购物车商品操作', res);
            });

            const totalNumbers = this.data.cartidsList.reduce((acc, curr) => acc + parseInt(curr.numbers), 0);
            console.log('totalPrice11', totalPrice)
            this.setData({
                cartTotalPrice: totalPrice.toFixed(2),
                totalNumbers: totalNumbers
            });
        });
    },
    // 批量删除购物-一件代发
    confirmDelete() {
        // 确认删除商品的逻辑处理

        console.log('执行删除商品操作', this.data.cartidsList);
        const cartids = this.data.cartidsList.map(item => item.id).join(',');

        console.log('cartids', cartids); // 输出结果为 "1690,1691"
        console.log('执行删除商品操作');
        ReDistributionMall({
            act: 'oneDelCart',
            cartids: cartids
        }).then(res => {
            console.log('批量删除购物', res)
            this.getShoppingCartList();

        });
    },
    /**
     * 前往支付回调函数方法
     */
    handleToPay(e) {
        const {
            value
        } = e.currentTarget.dataset
        console.log('value', e, this.data.cartidsList)
        if (value) {

            // 未选择需删除商品时返回用户提示
            if (this.data.cartidsList.length <= 0) return getApp().Tips({
                title: '请选择需要删除的商品！'
            })
            wx.showModal({
                title: '提示',
                content: '当前操作将做商品删除处理！是否继续执行？',
                success: (res) => {
                    if (res.confirm) {
                        this.confirmDelete();
                        const totalNumbers = this.data.cartidsList.reduce((acc, curr) => acc + parseInt(curr.numbers), 0);
                        console.log('totalPrice11', totalPrice)
                        this.setData({

                            totalNumbers: totalNumbers
                        });
                    } else if (res.cancel) {
                        console.log('用户点击了取消');
                    }
                }
            });

        } else {
            // 未选择商品时返回用户提示
            if (this.data.cartidsList.length <= 0) return getApp().Tips({
                title: '请选择商品！'
            })
            // 前往支付订单页面执行支付请求
            console.log('支付')
            let data = {
                address_id: this.data.addresid, //收货地址id
                coupons: '', //优惠券id，格式:1,2,3
                totalNumbers: this.data.totalNumbers
                // sealmanid
            }
            wx.navigateTo({
                url: `/pages/confirm_order_shipping/index?data=${JSON.stringify(data)}`,
            })
        }
    },
    /**
     * 删除购物车商品回调函数方法
     * @param {*} e 
     */
    handleDelCartGoods(e) {
        const {
            value
        } = e.currentTarget.dataset // 获取需的删除当前商品数据
        wx.showModal({
            title: '提示',
            content: '当前操作将做商品删除处理！是否继续执行？',
            success: (res) => {
                if (res.confirm) {
                    this.confirmDelete();
                    const totalNumbers = this.data.cartidsList.reduce((acc, curr) => acc + parseInt(curr.numbers), 0);
                    console.log('totalPrice11', totalPrice)
                    this.setData({

                        totalNumbers: totalNumbers
                    });
                } else if (res.cancel) {
                    console.log('用户点击了取消');
                }
            }
        });
    },
    /**
     * 计算页面可滚动区域的动态高度
     */
    computeScrollViewHeight() {
        let that = this
        let query = wx.createSelectorQuery().in(this)
        query.select('.header').boundingClientRect()
        query.select('.footer').boundingClientRect()
        query.exec(res => {
            let headerHeight = res[0].height;
            let footerHeight = res[1].height;
            let winHeight; // 窗口可使用高度
            let tabbarHeight; // 底部导航高度
            // let navTopHeight = headerHeight + tabsHeight
            wx.getSystemInfo({
                success: (res) => {
                    winHeight = res.windowHeight
                    tabbarHeight = res.windowHeight - res.safeArea.bottom // 计算底部导航总高度比变化
                }
            })
            let scrollHeight = winHeight - headerHeight - footerHeight - tabbarHeight;
            // 滚动区域高度
            that.setData({
                scrollViewHeight: scrollHeight + 60,
                tabbarHeight: tabbarHeight
            })
        })
    },
    /**
     * 打开提示弹窗回调函数方法
     */
    openShowModal() {
        // 进入页面如价格发生变动则提示用户
        if (this.data.price >= 0) {
            this.setData({
                showModal: true,
                modalTitle: "购物车价格变动提醒",
                isSlot: true,
                confirmText: "我知道了"
            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) { 
       
        console.log('进来',options)
        if (options.data) {
            let params = JSON.parse(options.data)
            this.data.params = {
                ...params
            }
            console.log('进', params, this.data.params)
            wx.nextTick(() => {
                this.setData({
                    addser:params.province + params.address 
                   
                })
            })
        }
        this.getShoppingCartList()
        this.getAddressres();
        this.getMallCartsp();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

        // this.openShowModal()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.computeScrollViewHeight()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})